#pragma once

#include <QObject>
#include <QTimer>
#include "mecameramanager.h"
#include "imagewindow.h"

class CameraService : public QObject
{
    Q_OBJECT

public:
    explicit CameraService(ImageWindow* imageWindow, QObject* parent = nullptr);
    ~CameraService();

    // 相机控制接口
    Q_INVOKABLE void initialize();
    Q_INVOKABLE void connectCamera(const QString& ipAddress = "");
    Q_INVOKABLE void disconnectCamera();
    Q_INVOKABLE void triggerSingleShot();
    Q_INVOKABLE void enumerateDevices();

    // 状态查询
    Q_INVOKABLE bool isCameraConnected() const;
    Q_INVOKABLE QString getCameraStatus() const;

    // 获取当前帧（用于后续处理）
    s_Image3dS getCurrentFrame() const { return m_currentFrame; }
    bool hasCurrentFrame() const { return m_hasCurrentFrame; }

signals:
    // 状态信号
    void cameraOpened(bool success, const QString& message);
    void cameraClosed();
    void frameAcquired(const s_Image3dS& frame);
    void errorOccurred(const QString& errorMessage);
    void devicesEnumerated(const s_DevicesInfo& devicesInfo);

    // 日志信号
    void logMessage(const QString& message);

private slots:
    void onCameraOpened(bool success, const QString& message);
    void onCameraClosed();
    void onFrameAcquired(const s_Image3dS& frame);
    void onErrorOccurred(const QString& errorMessage);
    void onDevicesEnumerated(const s_DevicesInfo& devicesInfo);
    void onDevicesEnumeratedForConnect(const s_DevicesInfo& devicesInfo);
    void onAutoConnectTimeout();

private:
    void setupConnections();
    void autoConnectToFirstCamera();
    void displayFrame(const s_Image3dS& frame);
    void log(const QString& message);

private:
    MeCameraManager* m_cameraManager;
    ImageWindow* m_imageWindow;
    QString m_lastCameraIp;
    bool m_hasCurrentFrame;
    s_Image3dS m_currentFrame;
    QTimer* m_autoConnectTimer;
};
